//
//  LHOAuthViewController.swift
//  sinaWeibo
//
//  Created by LiHong on 15/10/28.
//  Copyright © 2015年 LiHong. All rights reserved.
//

import UIKit
import SVProgressHUD

class LHOAuthViewController: UIViewController,UIWebViewDelegate {

    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "disMiss")
        view.backgroundColor = UIColor.whiteColor()
        
        let request = NSURLRequest(URL: LHNetWorkTools.shareInstance.oauthURL())
        webView.loadRequest(request)
    }
    // MARK: - UIWebViewDelegate 代理方法
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在玩命加载...", maskType: SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        
        if !urlString.hasPrefix(LHNetWorkTools.shareInstance.redirect_uri){
            return true
        }
        
        if let query = request.URL?.query{
            let nsQuery = query as NSString
            let codeString = "code="
            
            if nsQuery.hasPrefix(codeString){
                let code = nsQuery.substringFromIndex(codeString.characters.count)
             //   print("code = \(code)")
                loadAcessToken(code)
            }else{
                disMiss()
                return false
            }
        }

        return true
    }
    // MARK:- 加载授权
    /// 加载授权
    func loadAcessToken(code: String){
        LHNetWorkTools.shareInstance.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil {
                self.netError("网速不给力...")
                return
            }
     //       print(result)
            let account = LHUserAccount(dict: result!)
            account.saveAccount()
            
            account.loadUserInfo({ (error) -> () in
                if error != nil{
                    print("error = \(error)")
                    self.netError("加载用户数据出错...")
                    return
                }
            })
      //      account.description
           
            self.disMiss()
            (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootController(false)
        }
    }
    
    private func netError(message: String) {
        SVProgressHUD.showErrorWithStatus("\(message)")
        // TODO: BUG，显示时间很短
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            self.disMiss()
        });
    }

    /// 点击取消触发事件
    func disMiss(){
        dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }

    // MARK: - 懒加载
    lazy var webView: UIWebView = {
        return UIWebView()
    }()


}
